// pages/index/detail/detail.js
var that;
Page({
  data: {
    sk:'',
    params:[],
    commands:[],
    logs: [],
  },
  onLoad: function (options) {
    // 页面初始化 options为页面跳转所带来的参数
    that = this;
    that.sk = options.sk;
    console.log(options.sk)
    var paramList = [];

    //通过sk查出命令列表
    wx.request({
      url: 'https://open.iotechn.com/m.api',
      method: 'post',
      data: {
        _gp: 'device', _mt: 'getDeviceCommandsBySecretKey', secretKey:options.sk
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        var data = res.data;
        if(200 == data.code) {
          that.setData({
            commands: data.result
          })
        }else {
          wx.showToast({
            title: 'error:' + data.code,
          })
        }
      }
    });

    //通过sk查出参数列表
    wx.request({
      url: 'https://open.iotechn.com/m.api',
      method: 'post',
      data: {
        _gp: 'device', _mt: 'getDeviceParamsBySecretKey', secretKey: options.sk
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        var data = res.data;
        if (200 == data.code) {
          that.setData({
            params: data.result
          })
          paramList = data.result;
        } else {
          wx.showToast({
            title: 'error:' + data.code,
          })
        }
      }
    });

    //通过sk查处设备记录枚举
    wx.request({
      url: 'https://open.iotechn.com/m.api',
      method: 'post',
      data: {
        _gp: 'executor', _mt: 'getDeviceLogKeysBySk', secretKey: options.sk
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        var data = res.data;
        if (200 == data.code) {
          that.setData({
            logs: data.result
          })
          
        } else {
          wx.showToast({
            title: 'error:' + data.code,
          })
        }
      }
    });

    //TODO 聚合以上三个接口

    

    wx.onSocketMessage((res)=> {
      try {
        console.log(res)
        var obj = JSON.parse(res.data);
        if ('param' === obj.type) {
          for (var i = 0; i < paramList.length; i++) {
            if (paramList[i].name === obj.name) {
              paramList[i].paramValue = obj.value;
            }
          }
          
          that.setData({
            params:paramList
          })
        }
      }catch(e) {

      }
    });

    wx.onSocketError(()=> {
      wx.showToast({
        title: 'Socket连接错误',
      });
    });

    wx.onSocketClose(()=> {
      console.log('Socket已经断开')
    });

    wx.onSocketOpen(()=> {
      console.log('Socket已经打开');
      wx.sendSocketMessage({
        data: JSON.stringify({
          type: 1,
          secretKey: options.sk,
        }),
      })
    })
    
    wx.connectSocket({
      url: 'wss://open.iotechn.com/ws'
    });

    setInterval(()=>{
      //console.log('send heart')
      wx.sendSocketMessage({
        data: '{"type":0}',
      })
    },20000)
  },
  onReady: function () {
    // 页面渲染完成
    
  },
  onShow: function () {
    // 页面显示
  },
  onHide: function () {
    // 页面隐藏
  },
  onUnload: function () {
    // 页面关闭
    wx.closeSocket({
      
    })
  },
  onShareAppMessage: function () {
    return {
      title: 'iotechn控制器',
      path: '/pages/index/index',
      success: function (res) {
        // 分享成功
      },
      fail: function (res) {
        // 分享失败
      }
    }
  },

  clickLogHandler: function(e) {
    var sk = that.sk;
    var key = e.currentTarget.dataset.key;
    wx.navigateTo({
      url: 'log/log?sk=' + sk + '&key=' + key
    });
  },

  clickCommandHandler: function(e) {
    var cmd = e.currentTarget.dataset.cmd;
    wx.request({
      url: 'https://open.iotechn.com/m.api',
      data: {
        _gp: 'device', _mt: 'sendMsgToDevice', secretKey: that.sk, msg: cmd, qos: 1
      },
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        var data = res.data;
        if(200 == data.code) {
          wx.showToast({
            title: '' + data.result,
          })
        } else {
          wx.showToast({
            title: 'error:' + data.code,
          })
        }
      }
    })
  }
  
})